#include "MessageManager.h"
#include "MessageReceiver.h"
#include "Define.h"

MessageManager::MessageManager()
{
}

MessageManager::~MessageManager()
{
	if (_thread != NULL)
		delete _thread;
}

bool MessageManager::Initialize()
{
	int init = false;
	_thread = new QThread;
	if (_thread != NULL)
	{
		listen(QHostAddress::Any, MSG_PORT);
		moveToThread(_thread);
		_thread->start();
		init = true;
	}
	return init;
}

void MessageManager::SendMessage(QHostAddress addr, QByteArray stream)
{
	_socket.connectToHost(addr, MSG_PORT);
	if (_socket.write(stream) == -1)
		emit sigNotice("MessageManager::SendMessage() : write failed");
	_socket.disconnectFromHost();
}

void MessageManager::incomingConnection(int socketDescriptor)
{
	_mutex.lock();
	MessageReceiver *receiver = new MessageReceiver;
	if (receiver != NULL)
	{
		if (receiver->Initialize(socketDescriptor))
		{
			connect(receiver, SIGNAL(sigStreamReceived(QByteArray)), this, SLOT(OnSigStreamReceived(QByteArray)));
			_msgTask.append(receiver);
		}
		else
			emit sigNotice("MessageManager::incomingConnection() : error");
	}
	_mutex.unlock();
}

bool MessageManager::DeleteTask(MessageReceiver* receiver)
{
	return _msgTask.removeOne(receiver);
}

void MessageManager::OnSigStreamReceived(QByteArray stream)
{
	MessageReceiver *receiver = qobject_cast<MessageReceiver *>(sender());
	if (receiver != NULL)
	{
		emit sigMesasgeReceived(stream);
		DeleteTask(receiver);
	}
	else
		qDebug() << "MessageManager::OnSigStreamReceived() : DeleteTask() failed";
}
